package com.dream.myqiyi.ui;

import java.util.ArrayList;
import java.util.List;

import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.TagModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.TagService;
import com.dream.myqiyi.util.StringUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TagSelectActivity extends Activity {
	private NoteModel currNote;
	private List<TagModel> noteTags;
	
	private TextView etSelectTagsName;

	// search
	private ListView searchList = null;
	private String searchKeyword;
	private ArrayList<Item> searchResult = new ArrayList<Item>();
	private TagSelectAdapter searchAdapter;		// 数据适配器
	private AutoCompleteTextView searchAutoEdit;//搜索文本框
	private RelativeLayout newTagLayout;
	private TextView newTagText;

	// all
	private ListView allList;
	private ArrayList<Item> tagList = new ArrayList<Item>();
	private TagSelectAdapter allAdapter;

	private static final int DIALOG_FIND = 2;
	

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tag_select_activity);

		initUI();
		
		initUIData();

		doUpdate();
	}
	
	private void initUIData() {
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
		currNote = noteSrv.getCurrNoteModel();
		noteTags = tagSrv.getNoteTags(currNote.getGuid());

		updateCurrTagsUI();
		
		updateUIData(false);
	}
	private void updateUIData(boolean isSearch) {
		if (isSearch) {
			newTagLayout.setVisibility(View.VISIBLE);
			searchList.setVisibility(View.VISIBLE);
			allList.setVisibility(View.GONE);
		} else {
			newTagLayout.setVisibility(View.GONE);
			searchList.setVisibility(View.GONE);
			allList.setVisibility(View.VISIBLE);
		}

	}
	private void initUI() {
		//etSearchKeywords = (EditText)findViewById(R.id.search_keywords_et);
		etSelectTagsName = (TextView)findViewById(R.id.selected_notebook_name_tv);
		// back
		findViewById(R.id.back_button).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
				tagSrv.saveNoteTags(currNote.getGuid(), noteTags);

				Intent intent = new Intent(TagSelectActivity.this, NoteInfoActivity.class);
				TagSelectActivity.this.setResult(NoteInfoActivity.TAG_SELECTED_RESULT, intent);
				TagSelectActivity.this.finish();
			}
			
		});
		// search
		findViewById(R.id.search_button).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				searchKeyword = searchAutoEdit.getText().toString();
				if (searchKeyword.equals("")) {
					BaseApp.showToast("请输入您要查找的内容");
				} else {
					//请求数据(从新执行一个任务)
					new SearchTagTask().execute("");
				}
				
				// TODO 处理搜索结果
			}
		});
		
		//搜索文本框
		searchAutoEdit=(AutoCompleteTextView) findViewById(R.id.search_Keywords);
		searchAutoEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				searchKeyword = s.toString();
				if (StringUtils.isNull(searchKeyword)) {
					updateUIData(false);
				} else {
					updateUIData(true);
					new SearchTagTask().execute("");
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			} 
		});
		//搜索结果
		newTagLayout = (RelativeLayout)findViewById(R.id.add_no_search_layout);
		findViewById(R.id.add_no_search_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
				TagModel tag = tagSrv.addTag(newTagText.getText().toString());
				addTag(tag);
				newTagLayout.setVisibility(View.GONE);
				new SearchTagTask().execute("");
			}
		});
		newTagText = (TextView)findViewById(R.id.no_search_tv);
		
		searchList=(ListView)findViewById(R.id.searchlist);
		searchAdapter = new TagSelectAdapter(TagSelectActivity.this, R.layout.list_item_multi_select, searchResult);
		searchList.setAdapter(searchAdapter);
		searchList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Item item = searchAdapter.getItem(position);
				item.b = !item.b;//取反
				if (item.b) {
					addTag(item.tag);
				} else {
					removeTag(item.tag);
				}
				updateSearchAdapter();    					
			}
		});
		
		
		// 所有记事本
		allList = (ListView)findViewById(R.id.tag_list);
		allAdapter = new TagSelectAdapter(TagSelectActivity.this, R.layout.list_item_multi_select, tagList);
		allList.setAdapter(allAdapter);
		allList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Item item = allAdapter.getItem(position);
				item.b = !item.b;//取反
				if (item.b) {
					addTag(item.tag);
				} else {
					removeTag(item.tag);
				}
				updateAllAdapter();    					
			}
		});
	}
	
	private void updateCurrTagsUI() {
		String disp = "";
		for (TagModel t : noteTags) {
			if (disp.equals("")) {
				disp = t.getName();
			} else {
				disp = disp + ", " + t.getName();
			}
		}
		etSelectTagsName.setText(disp);
	}
	
	private void addTag(TagModel t) {
		boolean hasTag = false;
		for (TagModel tag : noteTags) {
			if (t.getGuid().equals(tag.getGuid())) {
				hasTag = true;
				break;
			}
		}
		if (!hasTag) {
			noteTags.add(t);
		}
		updateCurrTagsUI();
	}
	
	private void removeTag(TagModel t) {
		for (int i=0; i<noteTags.size(); ++i) {
			if (t.getGuid().equals(noteTags.get(i).getGuid())) {
				noteTags.remove(i);
				break ;
			}
		}
		updateCurrTagsUI();
	}
	
	private void doUpdate() {
		new GetTagsTask().execute("");
	}

	private class GetTagsTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {		 
			// 获取数据
			loadData();
			return "";
		}

		@Override
		protected void onPreExecute() {
			//showDialog(DIALOG_LOAD);
			//loadmore_btn.setText("loading ...");
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			if(tagList.size()==0){
				//emptytextView.setVisibility(View.VISIBLE);
			}
			else{
				updateAllAdapter();
			}
			
			allAdapter.notifyDataSetChanged();// 通知adapter数据变化
			//lvNotebook.setSelection(visibleLast - visibleCount + 1);
			
			//loadmore_btn.setText("Load More");
			//removeDialog(DIALOG_LOAD);
			
			String tagNames = "";
			for (TagModel t :noteTags) {
				tagNames += t.getName() + "; ";
			}
			etSelectTagsName.setText(tagNames);

		}
	}

	private void loadData() {
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
		if (noteSrv == null || tagSrv == null) {
			return ;
		}
		NoteModel note = noteSrv.getCurrNoteModel();
		tagList.clear();
		if (note != null) {
			ArrayList<TagModel> allTags = tagSrv.getAllTags();
			for (TagModel t : allTags) {
				if (noteTags.contains(t)) {
					tagList.add(new Item(t, true));
				} else {
					tagList.add(new Item(t, false));
				}
			}
		}		
	}

	//刷新适配器
	public void updateAllAdapter() {
		allAdapter.notifyDataSetChanged();
	}
	public void updateSearchAdapter() {
		searchAdapter.notifyDataSetChanged();
	}

	private class SearchTagTask extends AsyncTask<String, String, String> {
		private TagModel searchTag;
		public String doInBackground(String... params) {
			TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
			searchResult.clear();
			if (tagSrv != null) {
				ArrayList<TagModel> tags = tagSrv.getAllTags();
				for (TagModel tag : tags) {
					if (tag.getName().indexOf(searchKeyword) != -1) {
						if (tag.getName().equals(searchKeyword)) {
							searchTag = tag;
						}
						if (noteTags.contains(tag)) {
							searchResult.add(new Item(tag, true));
						} else {
							searchResult.add(new Item(tag, false));
						}
					}
				}
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			//showDialog(DIALOG_FIND);
			searchTag = null;
			newTagLayout.setVisibility(View.GONE);
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			//removeDialog(DIALOG_FIND);
			
            //通知适配器，发现改变操作
			searchAdapter.data = searchResult;
            searchAdapter.notifyDataSetChanged();	
            
            if (searchTag == null) {
            	newTagLayout.setVisibility(View.VISIBLE);
            	newTagText.setText(searchKeyword);
            } else {
            	newTagLayout.setVisibility(View.GONE);
            }
		}
	}


	private class TagSelectAdapter extends ArrayAdapter<Item>{
		private ArrayList<Item> data;
        private int layoutId;

		class TagSelectHolder {
			public CheckBox cbSelect = null;
			public TextView  tvTagName = null;

		}

        public TagSelectAdapter(Activity a, int layout, ArrayList<Item> d) {
        	super(a, layout, d);
			data = d;
			layoutId = layout;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
        	TagSelectHolder holder;
			if(view == null || (holder=(TagSelectHolder)view.getTag()) == null){
				holder = new TagSelectHolder();
				view = getLayoutInflater().inflate(layoutId, null);
				holder.cbSelect = (CheckBox) view.findViewById(R.id.select_cb);
				holder.tvTagName = (TextView) view.findViewById(R.id.name_tv);
				view.setTag(holder);
			}

			final TagModel newTag = data.get(position).tag;
			holder.cbSelect.setChecked(data.get(position).b);
			if (newTag != null) {
				holder.tvTagName.setText(newTag.getName());
			}
			return view;
		}
    }

	class Item{
		public TagModel tag;
		public boolean b = false;
		public Item(TagModel tag,boolean b){
			this.tag = tag;
			this.b = b;
		}
	}

	// 弹出"查看"对话框
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FIND: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("正在查找...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

}
